package cool.zhoujie.address.viewmodel;

import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.navigation.Navigation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cool.zhoujie.address.MyApplication;
import cool.zhoujie.address.R;
import cool.zhoujie.address.db.Address;
import cool.zhoujie.address.db.AddressDao;
import cool.zhoujie.address.db.AddressDatabase;

public class NewFragmentViewModel extends ViewModel {

    public String name = "";
    public String phone = "";
    public String region = "";
    public String detail = "";

    private AddressDao mDao;

    private boolean isDefault = false;

    public MutableLiveData<Boolean> isdefault = new MutableLiveData<>();

    public NewFragmentViewModel() {
        mDao = AddressDatabase.getInstance().mAddressDao();
        isdefault.setValue(isDefault);
    }

    public void isDefault() {
        isDefault = !isDefault;
        isdefault.setValue(isDefault);
    }

    public void save(final View view) {
        if (!checkInputNull()) {
            Address address = new Address(name, phone, region, detail, isDefault);
            mDao.insert(address);
            Navigation.findNavController(view).navigate(R.id.showFragment);
        }
    }

    public void navigate(View view) {
        Navigation.findNavController(view).navigate(R.id.action_newFragment_to_showFragment);
    }

    private boolean checkInputNull() {
        if (isEmpty(name, "收货人姓名")) {
            return true;
        }
        if (isEmpty(phone, "手机号码")) {
            return true;
        }
        if (!isPhone(phone)) {
            return true;
        }
        if (isEmpty(region, "所在地区")) {
            return true;
        }
        return isEmpty(detail, "详细地址");
    }

    private boolean isPhone(String phone) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$");
        Matcher m = p.matcher(phone);
        if (!m.matches()) {
            Toast.makeText(MyApplication.getContext(), "手机号码格式不对", Toast.LENGTH_SHORT).show();
        }
        return m.matches();
    }

    //检测字符串不空
    private boolean isEmpty(String string,String tag) {
        if (string.isEmpty()) {
            Toast.makeText(MyApplication.getContext(), tag + "不能为空", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            return false;
        }
    }
}
